package cn.edu.bupt.freewings.forum.server.rest.providers;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;

import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;

import com.google.protobuf.Message;
import cn.edu.bupt.freewings.forum.common.format.XMLFormatter;

import com.google.protobuf.Descriptors.FieldDescriptor;


@Produces("application/xml")
@Provider
public class XMLWriter implements MessageBodyWriter<Message>{

	static MediaType XMLMediaType = MediaType.APPLICATION_XML_TYPE; 
	
	public long getSize(Message message, Class<?> clasz, Type type,
			Annotation[] annotations, MediaType mediaType) {
		return -1;
	}

	public boolean isWriteable(Class<?> clasz, Type type, Annotation[] annotations,
			MediaType mediaType) {
		return Message.class.isAssignableFrom(clasz) && mediaType.isCompatible(XMLMediaType);
	}

	public void writeTo(Message message, Class<?> clasz, Type type,
			Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
			OutputStream outputStream) throws IOException, WebApplicationException {
		for(FieldDescriptor des : message.getAllFields().keySet()){
			System.out.println(des.getName());
		}
		XMLOutputter xmlOutPutter = new XMLOutputter(Format.getPrettyFormat());
		xmlOutPutter.output(XMLFormatter.toXMLDocument(message), outputStream);
	}

}
